package com.zhao.newcoder.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.lambdaworks.crypto.SCryptUtil;
import com.zhao.newcoder.DTO.User;
import com.zhao.newcoder.Soup.Constants;
import com.zhao.newcoder.config.WxMaConfiguration;
import com.zhao.newcoder.Repository.UserRepository;
import com.zhao.newcoder.controller.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.UUID;

@RestController
@Slf4j
@CrossOrigin
@Api(value = "微信获取信息接口", tags = "面经获取openid和sessionKey和登录获取用户相关接口")
public class WxApiController extends BaseController {

    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    UserRepository userRepository;
    /**
     * 登陆接口
     */
    @GetMapping("/login")
    @ApiOperation(value = "获取openid和session")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "前端获取的code码")

    })
    public WxMaJscode2SessionResult login(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(Constants.appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            log.info(session.getSessionKey());
            log.info(session.getOpenid());
            return  session;
            //TODO 可以增加自己的逻辑，关联业务相关数据
            //return JsonUtils.toJson(session);
        } catch (WxErrorException e) {
            log.error(e.getMessage(), e);
            //return e.toString();
        }
        return  null;
    }

    /**
     * <pre>
     * 获取用户信息接口
     * </pre>
     */
    @PostMapping("/info")
    @ApiOperation(value = "获取用户昵称等信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openid", value = "微信openid"),
            @ApiImplicitParam(name = "gender", value = "性别"),
            @ApiImplicitParam(name = "encryptedData", value = "加密数据"),
            @ApiImplicitParam(name = "iv", value = "不知道啥东西"),
            @ApiImplicitParam(name = "location", value = "地址"),
            @ApiImplicitParam(name = "avatarUrl", value = "头像地址"),
            @ApiImplicitParam(name = "sessionKey", value = "回话Key,login接口传过来的v")

    })
    public User info(String openid,Integer gender,String encryptedData,
                     String iv,String location,
                     String avatarUrl,String sessionKey) {

        log.error(avatarUrl);
        final WxMaService wxService = WxMaConfiguration.getMaService(Constants.appid);
        User userdb = userRepository.findUserByOpenid(openid);
        if (userdb==null){
          userdb = new User();
          // 解密用户信息
          WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);
          WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);
          userdb.setOpenid(openid);
          userdb.setLocation(location);
          BeanUtils.copyProperties(userInfo,userdb);
          userdb.setPhoneNumber(phoneNoInfo.getPhoneNumber());
          userdb.setGender(gender);
          userdb.setId(UUID.randomUUID().toString());
          //TODO 默认密码wx123456，后期添加密码修改功能供用户自行修改
          userdb.setPassword(SCryptUtil.scrypt("wx123456",32768,8,1));
          userRepository.save(userdb);
        }
        //TODO 获取用户信息存入session，使其他接口能够认证通过，后期需要通过其他方式处理，最好不用session方式
//        HttpSession session = request.getSession(false);
//        if(session!=null){
//            session.invalidate();
//        }
//        request.getSession(true).setAttribute("user",userdb.buildUserResponse());

        String url = "https://pa.kobefan.cn/user/login";
        MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
        map.add("phoneNumber",userdb.getId());
        map.add("password",userdb.getPassword());
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
        restTemplate.postForEntity(url, request,String.class);

        return userdb;

    }

}
